import warnings
warnings.warn("qturboframe.public_ui.ucf_h_ui.tree模块已被废弃，替代模块为qturboframe.public_ui.h_ui.tree", DeprecationWarning)

import re

from qturboframe.lib.report.log import logger
from qturboframe.lib.utils.check import CheckBasic
from qturboframe.lib.ranorex.exceptions import CsClientError
from qturboframe.lib.ranorex.web_element.ul_tag import UlTag
from qturboframe.lib.ranorex.web_element.span_tag import SpanTag
from ..ucf_base_element import BaseElement


class Tree(BaseElement, CheckBasic):
    '''hui的树形控件操作'''

    def __init__(self, element_para, father=None, timeout=10000):
        super().__init__(element_para, father, timeout)
        self._element = UlTag(self._element.control)

    def set_value_for_single(self, value):
        '''
        单选树形控件选择

        :Args:
         - value: 树形结构顺序点击的节点值，例：XX1/XX2/XX3

        :Example:
         - 例: tree.set_value_for_single('根节点/子节点/叶子节点')
        '''
        if value == '-':
            return
        value_list = value.split('/')
        # 打开树枝选项
        if len(value_list) > 1:
            last_value = value_list[-1]
            del value_list[-1]
            temp_ul = self._element
            for va in value_list:
                if temp_ul is not None:
                    up_div = self.__open_tree_node(temp_ul, va)
                    temp_ul = up_div
        else:
            temp_ul = self._element
            last_value = value_list[0]
        # 选择树叶选项
        if temp_ul is not None:
            logger.info('选择树形节点：' + last_value)
            SpanTag(temp_ul.find_element_by_attribute(
                'xpath', './li/div/span[@class~\'h-tree-title\' and @innertext=\'{}\']'.format(last_value),
                timeout=self.timeout).control).secure_click()
        else:
            raise CsClientError('中间节点未打开！')

    def set_value_for_multiple(self, value):
        '''
        多选树形控件选择

        :Args:
         - value: 树形结构顺序点击的节点值列表，例：['XX1/XX2/XX3', 'XX1/XX4/XX5']

        :Example:
         - 例: tree.set_value_for_multiple(['根节点1/子节点1/叶子节点1','根节点2/子节点2/叶子节点2'])
        '''
        # 遍历选项进行选择
        for single_value in value:
            if single_value == '-':
                continue
            value_list = single_value.split('/')
            # 打开树枝选项
            if len(value_list) > 1:
                last_value = value_list[-1]
                del value_list[-1]
                temp_ul = self._element
                for va in value_list:
                    if temp_ul is not None:
                        up_div = self.__open_tree_node(temp_ul, va)
                        temp_ul = up_div
            else:
                temp_ul = self._element
                last_value = value_list[0]
            # 选择树叶选项
            if temp_ul is not None:
                logger.info('选择树形节点：' + last_value)
                span_text = SpanTag(temp_ul.find_element_by_attribute(
                    'xpath', './li/div/span[@class~\'h-tree-title\' and @innertext=\'{}\']'.format(
                        last_value), timeout=self.timeout).control)
                span_checkbox = SpanTag(span_text.find_element_by_attribute(
                    'xpath', './preceding-sibling::label[@class~\'h-checkbox-wrapper\']/'
                             'span[@class~\'h-checkbox\']',
                    timeout=self.timeout).control)
                if 'h-checkbox-checked' not in span_checkbox.get_attribute('class'):
                    span_checkbox.secure_click()
            else:
                raise CsClientError('中间节点未打开！')

    def check_node_exist(self, value):
        '''
        校验树节点

        :Args:
         - value: 树形结构顺序点击的节点值列表，例：['XX1/XX2/XX3', 'XX1/XX4/XX5']

        :Example:
         - 例1: tree.check_node_exist('根节点/子节点/叶子节点')
         - 例2: tree.check_node_exist(['根节点1/子节点1/叶子节点1','根节点2/子节点2/叶子节点2'])
        '''
        if isinstance(value, str):
            value = [value]
            # 遍历选项进行选择
            for single_value in value:
                value_list = single_value.split('/')
                # 打开树枝选项
                if len(value_list) > 1:
                    last_value = value_list[-1]
                    del value_list[-1]
                    temp_ul = self._element
                    for va in value_list:
                        if temp_ul is not None:
                            up_div = self.__open_tree_node(temp_ul, va)
                            temp_ul = up_div
                else:
                    temp_ul = self._element
                    last_value = value_list[0]
                # 选择树叶选项
                if temp_ul is not None:
                    logger.info('选择树形节点：' + last_value)
                    span_text = SpanTag(temp_ul.find_element_by_attribute(
                        'xpath', './li/div/span[@class~\'h-tree-title\' and @innertext=\'{}\']'.format(
                            last_value), timeout=self.timeout).control)
                    if not span_text:
                        raise CsClientError('{}节点不存在！'.format(single_value))
                else:
                    raise CsClientError('中间节点未打开！')

    def __open_tree_node(self, ul, node_name):
        re_open = 'h-tree-arrow-open'
        title_span = SpanTag(ul.find_element_by_attribute('xpath',
            './li/div/span[@class~\'h-tree-title-parent\' and @innertext=\'{}\']'.format(node_name),
                                                          timeout=self.timeout).control)
        arrow_span = SpanTag(title_span.find_element_by_attribute(
            'xpath', './preceding-sibling::span[@class~\'h-tree-arrow\']', timeout=self.timeout).control)
        logger.debug("打开树形节点：" + node_name)
        if not re.search(re_open, arrow_span.get_attribute('class')):
            arrow_span.secure_click()
        next_ul = arrow_span.exist('xpath', './parent::div/following-sibling::ul', timeout=self.timeout)
        if next_ul:
            next_ul = UlTag(next_ul.control)
            if not next_ul.is_displayed():
                next_ul = None
        return next_ul
